package com.open.basic.tree;

import com.open.basic.json.JsonHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: system
 * @Date: 2024/4/24 22:16
 * @Version: V1.0
 * @description: desc:
 */

public class TreeUtil {

    public static List<TreeModel> getTree(List<TreeModel> listNode) {
        List<TreeModel> resultList = new ArrayList<>();
        listNode.stream().filter(node -> node.getPid().equals("0")).collect(Collectors.toList())
                .forEach(r -> {
                    TreeModel areaTreeResult = TreeUtil.packageTree(listNode, r);
                    resultList.add(areaTreeResult);
                });
        resultList.get(0).setDisabled(true);
        return resultList;
    }

    public static TreeModel packageTree(List<TreeModel> TreeModelList, TreeModel rootTreeModel) {
        if (TreeModelList != null && TreeModelList.size() > 0) {
            TreeModelList.forEach(TreeModel -> judgeObj(TreeModel, rootTreeModel));
            if (rootTreeModel.getList() != null && rootTreeModel.getList().size() > 0) {
                rootTreeModel.getList().forEach(r -> packageTree(TreeModelList, r));
            }
        }
        return rootTreeModel;
    }

    public static void judgeObj(TreeModel TreeModel, TreeModel rootTreeModel) {
        List<TreeModel> children = rootTreeModel.getList();
        if (children == null) {
            children = new ArrayList<>();
        }
        if (TreeModel != null && !TreeModel.getPid().isEmpty() && rootTreeModel.getId().equalsIgnoreCase(TreeModel.getPid())) {
            children.add(TreeModel);
            rootTreeModel.setList(children);
        }
    }

    public static void main(String[] args) {
        //封装数据
        List<TreeModel> listNode = new ArrayList<>();
        listNode.add(new TreeModel("1", "0", "parent", false));
        listNode.add(new TreeModel("88", "0", "parent", false));

        listNode.add(new TreeModel("2", "1", "second1", false));
        listNode.add(new TreeModel("3", "2", "second2", false));

        listNode.add(new TreeModel("4", "2", "three1", false));
        listNode.add(new TreeModel("5", "2", "three2", false));

        listNode.add(new TreeModel("6", "3", "three3", false));
        listNode.add(new TreeModel("7", "3", "three4", false));


        listNode.add(new TreeModel("8", "6", "four1", false));
        listNode.add(new TreeModel("9", "6", "four2", false));

        listNode.add(new TreeModel("10", "9", "five1", false));
//转换为tree


        List<TreeModel> tree = getTree(listNode);
        System.out.println(JsonHelper.toJson(tree));
    }
}
